package com.korosmatick.samplejms.jms;

import javax.annotation.PostConstruct;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import com.korosmatick.samplejms.domain.DummyMessage;

@Component
public class JMSMessageSender {
	
	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private Destination destination;
	
	
	@PostConstruct
	void initiateDummyMessages(){
		DummyMessage dummyMessage;
		for (int i = 0; i < 100; i++) {
			dummyMessage = new DummyMessage();
			dummyMessage.setId(i);
			dummyMessage.setContent("Dummy Content " + i);
			
			System.out.println("Sending Dummy Messge: " + i);
			
			sendDummyMessage(dummyMessage);
		}
	}

	public void sendDummyMessage(final DummyMessage dummyMessage) {
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				
				MapMessage message = session.createMapMessage();
				message.setInt("id", dummyMessage.getId());
				message.setString("content", dummyMessage.getContent());
				return message;
			}
		});
	}

}
